package com.chukun.flink.stream.window.process.windows;

import com.chukun.flink.stream.window.source.SourceForWindow;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.java.tuple.Tuple3;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.assigners.TumblingProcessingTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;

/**
 * @author chukun
 * @version 1.0.0
 * @description 窗口 reduce 函数操作
 * @createTime 2022年05月22日 23:38:00
 */
public class WindowReduceOperator {

    public static void main(String[] args) throws Exception {

        // 创建运行环境
        final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        // 添加数据源
        DataStreamSource<Tuple3<String, Integer, String>> stremSource = env.addSource(new SourceForWindow(1000, false));

        // 根据数据流中的元素f0字段作为作为key对数据流分组
        DataStream<Tuple3<String, Integer, String>> reduceStream = stremSource.keyBy((key) -> key.f0)
                .window(TumblingProcessingTimeWindows.of(Time.seconds(5)))
                // 对窗口应用ReduceFunction窗口函数，输出每个窗口中f1字段值最小的元素
                .reduce(new ReduceFunction<Tuple3<String, Integer, String>>() {
                    @Override
                    public Tuple3<String, Integer, String> reduce(Tuple3<String, Integer, String> value01, Tuple3<String, Integer, String> value02) throws Exception {
                        return value01.f1 > value02.f1 ? value01 : value02;
                    }
                });
        reduceStream.print("窗口-reduce计算: ");

        env.execute("WindowReduceOperator");
    }
}
